package login;

import java.io.*;
import java.util.ArrayList;

/**
 * Created by dllo on 18/4/16.
 */


public class IOUtils {

    public static final String FILE_NAME = "user.txt"; // 创建一个常量

    /**
     * 存储用户信息
     *
     * @param user 要存储的用户信息
     */
    public static void saveUser(User user) {  // 写流方法
        File file = new File(FILE_NAME); // 查询这个文件
        OutputStream os = null; // 输出流=空
        OutputStreamWriter osw = null;
        PrintWriter pw = null;

        try {
            if (!file.exists()) { // 判断这个文件是否存在
                file.createNewFile(); // 不存在建一个文件
            }
            os = new FileOutputStream(file,true); // 打开file这个文件的输出流
            osw = new OutputStreamWriter(os);
            pw = new PrintWriter(osw);

            String userInfo = user.getUsername() + ":" + user.getPwd() ;
            pw.println(userInfo);
//            os.write(userInfo.getBytes()); // 写流

        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            closeAll(pw);
        }
    }

    public static ArrayList<User> initUsers() {
        ArrayList<User> users = new ArrayList<>();
        File file = new File(FILE_NAME);
        if (!file.exists()) {
            return users;
        }
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;

        try {
            is = new FileInputStream(file);
            isr = new InputStreamReader(is);
            br = new BufferedReader(isr);

            String line = "";
            while ((line = br.readLine()) != null){
                User user = new User();
                String[] info = line.split(":");
                if (info.length == 2){
                    user.setUsername(info[0]);
                    user.setPwd(info[1]);
                    users.add(user);
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeAll(br);
        }
        return users;
    }

    public static void closeAll(Closeable... closeables) {
        if (closeables == null) {
            return;
        }
        for (Closeable closeable : closeables) {
            if (closeable != null) {
                try {
                    closeable.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
